#!/bin/bash

echo "================================"
echo "    无人机管理系统启动脚本       "
echo "================================"

# 设置当前目录为脚本所在目录
cd "$(dirname "$0")"

# 检查Python是否安装
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到Python3环境，请先安装Python 3.7+"
    exit 1
fi

# 删除旧的虚拟环境（如果存在）
if [ -d "venv" ]; then
    echo "删除旧的虚拟环境..."
    rm -rf venv
    if [ $? -ne 0 ]; then
        echo "警告: 无法删除旧的虚拟环境，请手动删除后重试"
        read -p "按Enter键继续..."
    fi
fi

# 创建虚拟环境
echo "创建虚拟环境..."
python3 -m venv venv
if [ $? -ne 0 ]; then
    echo "错误: 创建虚拟环境失败"
    exit 1
fi

# 激活虚拟环境
echo "激活虚拟环境..."
source venv/bin/activate
if [ $? -ne 0 ]; then
    echo "错误: 激活虚拟环境失败"
    exit 1
fi

# 升级pip
echo "升级pip..."
pip install --upgrade pip
if [ $? -ne 0 ]; then
    echo "警告: 升级pip失败，将继续尝试安装依赖"
fi

# 安装依赖
echo "安装项目依赖..."
pip install -r requirements.txt
if [ $? -ne 0 ]; then
    echo "错误: 安装依赖失败"
    exit 1
fi

# 初始化数据库
echo "初始化数据库..."
python initialize_database.py
if [ $? -ne 0 ]; then
    echo "警告: 数据库初始化过程中出现错误"
    read -p "按Enter键继续..."
fi

# 启动应用
echo "启动后端服务..."
echo "服务地址: http://localhost:8000"
echo "API文档: http://localhost:8000/docs"
uvicorn main.py